申請 LINE Message Bot 並取得 access token,可參考以下文章說明:
👉 LINE Messaging API 註冊申請
我想要一個簡單的功能:每天早上收到 LINE 通知,提醒我今天有哪些行事曆事件。
一開始的程式邏輯還包含「建立行事曆事件」的部分,但對我來說用不到。於是我請 ChatGPT 協助我簡化,只留下「讀取事件」與「發送 LINE 通知」兩個功能。
這是我後來使用的主要功能流程:
我平常不只使用「主要行事曆」,還有像是「家庭」、「朋友」等與他人共用的日曆,最一開始的程式只能抓 getDefaultCalendar()
,但那只抓得到主行事曆。
於是我改用 getAllCalendars()
,可以抓到我帳號有權限的所有日曆,包括共用日曆與 Google Classroom 行事曆。
如果妳也想抓全部的行事曆事件,這段程式碼會是好用的起點。
const LINE_CHANNEL_ACCESS_TOKEN = '...';
const USER_ID = '...';
function sendTodayEventsToLine() {
const allCalendars = CalendarApp.getAllCalendars();
const today = new Date();
const start = new Date(today.setHours(0, 0, 0, 0));
const end = new Date(today.setHours(23, 59, 59, 999));
const allEvents = [];
allCalendars.forEach(calendar => {
const events = calendar.getEvents(start, end);
events.forEach(e => {
allEvents.push({
calendarName: calendar.getName(),
title: e.getTitle(),
startTime: Utilities.formatDate(e.getStartTime(), Session.getScriptTimeZone(), "HH:mm"),
endTime: Utilities.formatDate(e.getEndTime(), Session.getScriptTimeZone(), "HH:mm")
});
});
});
if (allEvents.length === 0) {
sendLineMessage("📅 今天沒有排定的行事曆事件", LINE_CHANNEL_ACCESS_TOKEN, USER_ID);
return;
}
const lines = allEvents.map(e =>
`📌【${e.calendarName}】${e.title}(${e.startTime} - ${e.endTime})`
);
const message = `📅 今天所有行事曆的事件(共 ${allEvents.length} 筆):\n\n${lines.join("\n")}`;
sendLineMessage(message, LINE_CHANNEL_ACCESS_TOKEN, USER_ID);
}
function sendLineMessage(message, token, userId) {
const url = "https://api.line.me/v2/bot/message/push";
const payload = {
to: userId,
messages: [{ type: "text", text: message }]
};
const options = {
method: "post",
contentType: "application/json",
payload: JSON.stringify(payload),
headers: { Authorization: "Bearer " + token }
};
UrlFetchApp.fetch(url, options);
}
可以在 Apps Script 的「觸發器」設定每天 08:00 執行 sendTodayEventsToLine()
,自動推播提醒,讓一天從清楚的行程開始。
如果妳也想試著用 GPT 幫忙撰寫 Apps Script,可以這樣問:
請幫我寫一段 Google Apps Script,抓取我今天所有行事曆的事件,並用 LINE Messaging API 發送訊息。
進階功能也能詢問:
請幫我修改這段程式碼,只抓「家庭」與「朋友」行事曆的事件,並附上事件地點。